package com.wsd.service.impl;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.wsd.bean.Category;
import com.wsd.dao.CategoryDaoInterface;
import com.wsd.service.CategoryService;

public class CategoryServiceImpl implements CategoryService{
	private CategoryDaoInterface categoryDAO;
	public Category getRootCategorie() {
		return categoryDAO.findById(1);
	}
	
	public CategoryDaoInterface getCategoryDAO() {
		return categoryDAO;
	}
	public void setCategoryDAO(CategoryDaoInterface categoryDAO) {
		this.categoryDAO = categoryDAO;
	}

	public List<Category> saveCategories(List<Category> categories) {
		Category parent = null;
		for (Iterator iter = categories.iterator(); iter.hasNext();) {
			Category category = (Category) iter.next();
			if(parent == null){
				parent = categoryDAO.findById(category.getParent().getCId());
				categoryDAO.updateGt(parent.getRgt(),categories.size()*2);
			}
			if(categoryDAO.findByExample(category).size() == 0){
				categoryDAO.save(category);
				//category.setCategories(null);
				//category.setProductses(null);
			}else{
				//重复者删除
				iter.remove();
			}
			
		}
		return categories;
	}

	public void delCategory(Category category) {
		category = categoryDAO.findById(category.getCId());
		int rgt = category.getRgt();
		int lft = category.getLft();
		int range = rgt - lft + 1;
		categoryDAO.updateGt(rgt, -range);
		categoryDAO.delete(category);
	}

	public void update(Category category) {
		categoryDAO.update(category);
	}

	/* (non-Javadoc)
	 * @see com.wsd.service.CategoryService#findById(java.lang.Integer)
	 */
	public Category findById(Integer id) {
		return categoryDAO.findById(id);
	}

	/* (non-Javadoc)
	 * @see com.wsd.service.CategoryService#findByLevel(int)
	 */
	public List<Category> findByLevel(int level) {
		return categoryDAO.findByLevel(level);
	}

	/* (non-Javadoc)
	 * @see com.wsd.service.CategoryService#getParentCategorys(int)
	 */
	public Deque<Category> getParentCategorys(Category c) {
		Deque<Category> path = new LinkedList<Category>();
		while ( null != c.getParent()) {
			path.offerFirst(c);
			if(null == c.getParent() || 0 == c.getParent().getCId())
				break;
			c = c.getParent();
		}
		return path;
	}
}
